/*!
 @header RechargeViewController.m
 @author 周益
 @version 1.0.0 2013/02/27 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "RechargeViewController.h"
#import "JMFBase.h"
#import "YiJiPayPlugin.h"
#import "MoonHTTPRequest.h"

#define MAX_AMOUNT 2000.00
#define MIN_AMOUNT 1.00

#define UNION_TEMPLATE @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<upomp application=\'LanchPay.Req\' version=\'1.0.0\'>\
<merchantId>%@</merchantId>\
<merchantOrderId>%@</merchantOrderId>\
<merchantOrderTime>%@</merchantOrderTime>\
<sign>%@</sign>\
</upomp>"

//  -业务逻辑细节说明-
//
//  @abstract       充值

//  @discussion     用户在输入或者点击了正确的金额后，点击下一步时，首先会向服务器请求银联充值，然后获取此订单相应的商户订单信息，获取成功后，就会将信息一起push到银联插件中，让用户在插件中确认自己的充值信息是否正确。

//                  如果用户充值成功（此时的充值是指在银联上充值成功，而并非在服务器充值成功），此时main线程会sleep 5s（等待服务器处理此次转账业务），然后向服务器请求充值验证；
//                      如果用户充值失败，那么就直接提示给用户插件返回的相应失败描述。
//                  关于向服务器请求充值验证，一共有3种状态：充值处理中、充值失败和充值成功。不管验证结果是什么状态最后都会跳转到账户信息页面。
//                      充值成功后，要提示用户余额，充值失败提示用户充值成功，正在处理中。
//                  是否应该检查充值状态是通过设置_shouldCheckRecharge来判断，银联插件充值成功后，会回调returnWithResult方法，在方法里面，解析完XML后，将_shouldCheckRecharge设为YES，pop出银联插件后，在viewWillAppear中会根据_shouldCheckRecharge来处理是否向服务器请求验证用户的充值状态。
//                      

//  @notes          验证充值状态的时候应该重构，详情查看warning


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述


@interface RechargeViewController ()

@end

@implementation RechargeViewController
@synthesize shouldCheckRecharge = _shouldCheckRecharge;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //此时为第一次进入充值页面，禁止检查充值状态
    _shouldCheckRecharge = NO;
    
    //默认充值金额为100
    _amount = 100;
    
    self.title = _L(@"vc_title_045");
    
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //上半部分背景
    UIView *topBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0, 100.0f)];
    topBackgroundView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:topBackgroundView];
    
    
    //手动输入金额部分
    _amountTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300.0f, 30.0f)];
    _amountTextField.borderStyle = UITextBorderStyleRoundedRect;
    _amountTextField.font = _SYS_FONT_007;
    _amountTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _amountTextField.placeholder = _L(@"holder_10");   // 请输入充值金额
    _amountTextField.returnKeyType = UIReturnKeyDone;
    _amountTextField.keyboardType = UIKeyboardTypeDecimalPad;
    _amountTextField.text = @"500";
    _amountTextField.delegate = self;
    
    //最右侧加图片是以下代码
    UILabel *yuanLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 25.0f, 25.0f)];
    yuanLabel.text = @"元";
    yuanLabel.textColor = _SYS_COLOR_002;
    yuanLabel.font = _SYS_FONT_007;
    _amountTextField.rightView = yuanLabel;
    _amountTextField.rightViewMode = UITextFieldViewModeAlways;
    [topBackgroundView addSubview:_amountTextField];
    
    //YIJIPAY
    UIButton *yijipayButton = [[UIButton alloc] initWithFrame:CGRectMake(_amountTextField.frame.origin.x, _amountTextField.frame.origin.y + _amountTextField.frame.size.height + 10.0f, 142, 44.0f)];
    yijipayButton.tag = 1;
    [yijipayButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"more_btn_002_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [yijipayButton addTarget:self action:@selector(nextStepButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [topBackgroundView addSubview:yijipayButton];

    //unionPay
    UIButton *unionpayButton = [[UIButton alloc] initWithFrame:CGRectMake(168, yijipayButton.frame.origin.y, 142, 44.0f)];
    unionpayButton.tag = 2;
    [unionpayButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"more_btn_003_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [unionpayButton addTarget:self action:@selector(nextStepButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [topBackgroundView addSubview:unionpayButton];
    
    //温馨提示
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, topBackgroundView.frame.size.height + 5, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT - 44 - 5 - topBackgroundView.frame.size.height)];
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"recharge_tips" ofType:@"html"];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    _webView.scrollView.scrollEnabled = true;
    _webView.dataDetectorTypes = UIDataDetectorTypeNone;
    [self.view addSubview:_webView];
    
    //下半部分背景
//    UIView *bottomBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, topBackgroundView.frame.origin.y + topBackgroundView.frame.size.height + 10.0f, 320.0, _SYS_SCREEN_HEIGHT - 20.0f - 44.0f - topBackgroundView.frame.size.height - 10.0f)];
//    bottomBackgroundView.backgroundColor = [UIColor whiteColor];
//    
//    [self.view addSubview:bottomBackgroundView];
    
    //文字说明
//    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0, 40.0f)];
//    titleLabel.text = _L(@"title_15");   //温馨提示
//    titleLabel.font = _SYS_FONT_009;
//    titleLabel.textAlignment = NSTextAlignmentCenter;
//    
//    [bottomBackgroundView addSubview:titleLabel];
    
    //line
//    UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, titleLabel.frame.size.height + titleLabel.frame.origin.y + 10.0f, 320.0f, 1)];
//    lineImageView.image = [UIImage imageNamed:@"line_292"];
//    
//    [bottomBackgroundView addSubview:lineImageView];
    
    //内容
//    UILabel *firstPointLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, lineImageView.frame.origin.y + lineImageView.frame.size.height + 5.0f, 300.0f, 40.0f)];
//    firstPointLabel.text = _L(@"title_13");
//    firstPointLabel.font = _SYS_FONT_005;
//    firstPointLabel.numberOfLines = 0;
//    firstPointLabel.lineBreakMode = NSLineBreakByWordWrapping;
//    
//    [bottomBackgroundView addSubview:firstPointLabel];
//    
//    UILabel *secondPointLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, firstPointLabel.frame.origin.y + firstPointLabel.frame.size.height + 5.0f, 300.0f, 35.0f)];
//    secondPointLabel.text = _L(@"title_14");
//    secondPointLabel.font = _SYS_FONT_005;
//    secondPointLabel.numberOfLines = 0;
//    secondPointLabel.lineBreakMode = NSLineBreakByWordWrapping;
//    
//    [bottomBackgroundView addSubview:secondPointLabel];
    
    UIWindow* window = [[UIApplication sharedApplication].windows objectAtIndex:([UIApplication sharedApplication].windows.count - 1)];
    if(_HUD == nil){
        _HUD = [[MBProgressHUD alloc] initWithWindow:window];
    }
    [window addSubview:_HUD];
    _HUD.labelText = _L(@"title_loading_08");   //充值处理中...
    _HUD.mode = MBProgressHUDModeText;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    if (_shouldCheckRecharge) {
//        //充值成功
//        if ([_respCode isEqualToString:@"0000"]) {
//            
//            //等待5秒后，向服务器请求发送充值状态验证，再此期间让用户等待并显示充值处理中；
//            //直接返回当前用户的余额，客户端直接提示用户“充值成功”
//            //就提示用户“充值失败”
//            
//            [_HUD showAnimated:YES whileExecutingBlock:^{
//                sleep(5.0);
//            } completionBlock:^{
//                [self checkRechargeUnionpay:_merchantOrderId];
//            }];
//            
//            //充值失败
//        }
//        else{
//            [Helper showAlertWithTitle:@"" andMessage:_respDesc];
//        }
//    }
//}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent:(id)sender
{
    [self.navigationController dismissModalViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:true];
}

/*!
 @abstract 下一步按钮事件
 */
- (void)nextStepButtonEvent:(id)sender
{
    [_amountTextField resignFirstResponder];
    
    _amount = [_amountTextField.text floatValue];
    
    UIButton* button = (UIButton *)sender;
    
    if (_amount < MIN_AMOUNT) {
        
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_43")];   //充值金额不能少于1元
        return;
    }
    
    if (_amount > MAX_AMOUNT) {
        
        [Helper showAlertWithTitle:nil andMessage:_L(@"alert_31")];   //每日充值金额单笔不超过2000元，请重新输入充值金额
        return;
    }
    
    MoonHTTPRequest *request = [[MoonHTTPRequest alloc] init];
    request.URLString = button.tag == 1 ? _JSON_URL_ACCOUNT_RECHARGE_YIJIFUPAY : _JSON_URL_ACCOUNT_RECHARGE_UNIONPAY;
    request.progressOn = true;
    request.progressTitle = _L(@"title_loading_01");
    [request setParameter:@(_amount) forName:@"amount"];
    [request onSuccess:^(id result) {
        
        JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:result];
        if (jmf.status == JMStatusSucceed) {
            NSDictionary *data = [result objectForKey:@"data"];
            
            //获得进入重置插件必要的订单参数
            if (button.tag == 1) {
                
                //获得进入重置插件必要的订单参数
                _orderId = jmf.data[@"orderId"];
                NSString *partnerId = jmf.data[@"partnerId"];
                NSString *accessId = jmf.data[@"accessId"];
                NSString *yijifuUserId = jmf.data[@"yijifuUserId"];
                
                NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:partnerId, kYjParamPartnerID, _SYS_YIJIPAY_FLAG, kYjParamMode, _orderId, kYjParamOrderID, accessId, kYjParamAccessID, yijifuUserId, kYjParamUserID,nil];
                NSLog(@">>>>%@", params);
                int ret = [YiJiPayPlugin startPay:params viewController:self delegate:(id)self];
                if (!ret) {
                    
                    [Helper showAllTextDialog:@"抱歉，目前暂时不能支付，请稍后再试" inSeconds:3];
                }
                
            }
            else {
                
                NSString *merchantId = [data objectForKey:@"merchantId"];
                NSString *merchantOrderId = [data objectForKey:@"merchantOrderId"];
                NSString *merchantOrderTime = [data objectForKey:@"merchantOrderTime"];
                NSString *signAfterEncryption = [data objectForKey:@"sign"];
                
                NSString *order = [NSString stringWithFormat:UNION_TEMPLATE, merchantId, merchantOrderId, merchantOrderTime, signAfterEncryption];
                
                UIViewController *viewCtrl = [LTInterface getHomeViewControllerWithType:_SYS_PAY_FLAG strOrder:order andDelegate:self];
                [self.navigationController pushViewController:viewCtrl animated:YES];
            }
            
        }
        else {
            
            [Helper easyShowJMFStatus:jmf];
        }
    } onFailure:^(NSError *error) {
        
        [Helper showAlertWithTitle:_L(@"title_networkunavailabe") andMessage:Nil];
    }];
    [request asynchronous];
    
}

/*!
 @abstract 向服务器验证充值状态
 @param merchantOrderId 商户订单号
 */
- (void)checkRechargeUnionpay:(NSString *)merchantOrderId
{
    if (merchantOrderId == nil && merchantOrderId.length == 0) {
        
        NSLog(@"获取商户订单id失败");
        return;
    }
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_RECHARGE_CHECK_UNIONPAY];
    request.delegate = self;
    [request setValue:merchantOrderId forParameter:@"merchantOrderId"];
    [request asynchronous];
}

/*!
 @abstract 向服务器验证充值状态
 @param orderId 商户订单号
 */
- (void)checkRchargeYjfpay:(NSString *)orderId
{
    if (orderId == nil && orderId.length == 0) {
        
        NSLog(@"获取商户订单id失败");
        return;
    }
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_ACCOUNT_RECHARGE_CHECK_YIJIFUPAY];
    request.delegate = self;
    [request setValue:orderId forParameter:@"orderId"];
    [request asynchronous];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];

    if (jmf.status == JMStatusSucceed) {
        
        NSDictionary *data = (NSDictionary *)jmf.data;
        
        //获得充值状态
        NSInteger rechargeStatus = [[data objectForKey:@"status"] integerValue];
        
        NSString *alertMessage = nil;
        
        switch (rechargeStatus) {
                
                //充值处理中
            case 0:
            {
                [Helper showAlertWithTitle:nil andMessage:_L(@"alert_29")];
            }
                
                break;
                
                //充值成功
            case 1:
            {
                
                float balance = [[data objectForKey:@"balance"] floatValue];
                alertMessage = [NSString stringWithFormat:_L(@"tpl_06"), balance];   //@"余额为%.2f元"
                
                [Helper showAlertWithTitle:jmf.message andMessage:alertMessage];
                
            }
                break;
                
                //充值失败
            default:
            {
                [Helper showAlertWithTitle:nil andMessage:_L(@"alert_29")];
            }
                break;
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
    [self.navigationController popViewControllerAnimated:true];
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}


#pragma mark = UITextField Delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (_numInLabel == nil || [@"" isEqualToString:_numInLabel]) {
        
        _amount = 0.00f;
    }
    
    else if(_numInLabel != nil && !([@"" isEqualToString:_numInLabel])){
        
        _amount = [_numInLabel floatValue];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_numInLabel == nil) {
        _numInLabel = @"";
    }
    
    if (string == nil) {
        return NO;
    }
    
    _numInLabel = _amountTextField.text;
    
    //当string的长度不为0时，则说明用户当前正在输入金额
    if ([string length] != 0) {
        
        //输入时，将输入的数字添加到上一次输入的数字的末尾
        _numInLabel = [_numInLabel stringByAppendingString:string];
        
        //当string的长度为0时，则说明用户在删除上一次输入的数字
    }else{
        
        //删除时，去掉末尾的数字
        _numInLabel = [_numInLabel substringToIndex:range.location];
    }

    if ([_numInLabel floatValue] > MAX_AMOUNT) {
        
        [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_31")];

        //用户输入一个数字，使输入额度超过最大金额时，为保证用户此时点击下一步为正确的金额，所以要去掉刚刚用户输入的数字。
        _numInLabel = [_numInLabel substringToIndex:range.location];
        
        return NO;
    }
    
    _amount = [_numInLabel floatValue];
    
    return YES;
}

#pragma mark = LTInterface Delegate
- (void) returnWithResult:(NSString *)strResult
{    
    if (strResult == nil) {
        return;
    }
    
    //解析充值插件返回的xml文本
    NSData *xml = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xml];
    
    xmlParser.delegate = self;
    
    if ([xmlParser parse]) {
        NSLog(@"The XML is parsed.");
        
    } else{
        
        NSLog(@"Failed to parse the XML");
    }
#warning 此处和viewwillappear的充值状态的请求应该重构，应该找一处符合逻辑的地方写请求验证充值状态的代码
    _shouldCheckRecharge = YES;
    self.navigationController.navigationBarHidden = NO;
    
    if ([_respCode isEqualToString:@"0000"]) {
        [_HUD showAnimated:YES whileExecutingBlock:^{
            sleep(5.0);
        } completionBlock:^{
            [self checkRechargeUnionpay:_merchantOrderId];
            _shouldCheckRecharge = NO;
        }];
    }
}

#pragma mark - NSXMLParser Delegate

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
   namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
     attributes:(NSDictionary *)attributeDict
{
    _flag = YES;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (_flag) {
        _currentElementValue = string;
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"respCode"]) {
        _respCode = _currentElementValue;
    }else if ([elementName isEqualToString:@"respDesc"]){
        _respDesc = _currentElementValue;
    }else if ([elementName isEqualToString:@"merchantOrderId"]){
        _merchantOrderId = _currentElementValue;
    }
    
    _flag = NO;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_amountTextField resignFirstResponder];
    
}

#pragma mark - YiJiPayPlugin Delegate

- (void)YiJiPayPluginResult:(NSDictionary *)result
{
    
    if (result) {
        NSLog(@"充值结果%@", result);
        NSInteger status = [result[kYjResultStatus] integerValue];
        NSString *message = result[kYjResultMessage];
        
        if (200 == status) {
            
            [_HUD showAnimated:YES whileExecutingBlock:^{
                sleep(5.0);
            } completionBlock:^{
                [self checkRchargeYjfpay:_orderId];
//                _shouldCheckRecharge = NO;
            }];
        }
        
        else{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alertView show];
        }
    }
}


#pragma mark - UIWebView

//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSArray* parameters = [request.URL.relativeString componentsSeparatedByString:@":"];
//    
//    if ([parameters[0] isEqualToString:@"call"])
//    {
//        [UIApplication sharedApplication] openURL:[NSURL URLWithString:[@"tel://"]]
//    }
//    
//    return true;
//}

@end
